package com.bacga.abctest;

import com.bacga.abctest.util.Get;
import com.bacga.abctest.util.Post;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;

import java.time.LocalDateTime;
import java.util.Map;

@Component
@Slf4j
public class HttpExecutor implements Runnable{
    public interface HttpRequestListener {

        void report(int index, int count, String result, Long useTime);

        // public void finish();
    }

    public HttpExecutor() {
        super();
    }

    private HttpRequestListener httpListener;
    private int reqCount;
    private String requestURL;
    private Get get;
    private Post post;
    private Object param;

    public HttpExecutor(String url,Object param, int num, HttpRequestListener listener) {
        super();
        this.reqCount = num;
        this.requestURL = url;
        this.httpListener = listener;
        this.param = param;
        get = new Get();
        post = new Post();
    }

    @Override
    public void run() {
        if (param != null){
            postWork();
        }else {
            getWork();
        }



    }

    void getWork(){
        for (int i = 1; i <= reqCount; i++) {
            long beginTime = System.nanoTime();
            ResponseEntity result = null;
            long useTime;
            try {
                result = get.to(requestURL);
            } catch (RestClientException e) {
                log.error("请求超时！");
            }finally {
                useTime = (System.nanoTime() - beginTime) / 1000000l;
                httpListener.report(i, reqCount, result == null ? "" : result.getBody().toString(), useTime);
            }

        }
    }

    void postWork(){
        for (int i = 1; i <= reqCount; i++) {
            long beginTime = System.nanoTime();
            ResponseEntity result = null;
            long useTime;
            try {
                result = post.to(requestURL,param);
            } catch (RestClientException e) {
                log.error("请求超时！");
            }finally {
                useTime = (System.nanoTime() - beginTime) / 1000000l;
                httpListener.report(i, reqCount, result == null ? "" : result.getBody().toString(), useTime);
            }

        }
    }

}
